from datetime import datetime, timedelta
import time

# 时间格式转换成时间戳
def creatData(date_string):
    date_format = "%Y-%m-%d %H:%M:%S"

    # 将日期时间字符串转换为datetime对象
    date_time = datetime.strptime(date_string, date_format)

    # 将datetime对象转换为时间戳（毫秒）
    timestamp_ms = int(time.mktime(date_time.timetuple()) * 1000)

    print(f"The timestamp for '{date_string}' is: {timestamp_ms} milliseconds.")
    return timestamp_ms

# 时间戳转换成时间格式
def datetimeToTimestamp(timestamp):
    # 确保时间戳是整数并转换为秒
    timestamp = int(timestamp) / 1000

    # 转换为 datetime 对象
    dt_object = datetime.fromtimestamp(timestamp)

    # 格式化为指定的字符串格式
    formatted_date = dt_object.strftime("%Y-%m-%d %H:%M:%S")

    print(f"The datetime for '{timestamp}' is: {formatted_date} ")

# 最近时间多少天多少分钟步长的所有时间戳
def creatMinDatas(given_time_str,days,minutes):
    given_time = datetime.strptime(given_time_str, "%Y-%m-%d %H:%M:%S")

    # 计算给定时间之前7天的日期
    start_date = given_time - timedelta(days=days)

    # 生成从 start_date 到给定时间的每个分钟时间(直接打印，也可返回列表)
    min_data = []
    current_min = datetime(start_date.year, start_date.month, start_date.day, start_date.hour, start_date.minute)
    while current_min <= given_time:
        min_data.append(current_min.strftime("%Y-%m-%d %H:%M:%S"))
        current_min += timedelta(minutes=minutes)

    timestamps = []
    for mi in min_data:
        date_string = mi
        date_format = "%Y-%m-%d %H:%M:%S"
        # 将日期时间字符串转换为datetime对象
        date_time = datetime.strptime(date_string, date_format)

        # 将datetime对象转换为时间戳（毫秒）
        timestamp_ms = int(time.mktime(date_time.timetuple()) * 1000)
        print(timestamp_ms)
        timestamps.append(timestamp_ms)
    return timestamps

# 时间转换成时间戳
# given_time_str=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# creatData(given_time_str)

# 最近时间多少天多少分钟步长的所有时间戳（分钟） 可返回列表
# creatMinDatas(given_time_str,0.5,1)

# 时间撮转换成时间
# datetimeToTimestamp(1723257397843)

creatData('2024-09-05 12:14:20')